package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    /*
    * 新增菜品
    * */
    @Override
    @Transactional//有多个sql语句,所以要开启事务
    public void save(DishDTO dishDTO) {
        //1.将数据封装到Dish中
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //2.调用Mapper新增菜品数据
        dishMapper.save(dish);
        //3.补全每个口味中关联字段的菜品ID stream流开发
        List<DishFlavor> dishFlavors = dishDTO.getFlavors().stream().map(dishFlavor -> {
            dishFlavor.setDishId(dish.getId());
            return dishFlavor;
        }).collect(Collectors.toList());

        //4.调用Mapper批量插入
        dishFlavorMapper.saveBatch(dishFlavors);

    }

    /*
    * 菜品分类查询
    * */
    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        Page<DishVO> page =  dishMapper.page(dishPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }
/*
* 菜品删除
* */
    @Transactional
    @Override
    public void deleteWithDishFlavor(List<Long> ids) {
        //1.判断是否还有起售的菜品，有抛出异常结束
        for (Long id : ids) {
            Dish dish = dishMapper.getById(id);
            if (dish.getStatus() == StatusConstant.ENABLE){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }

        //2.判断菜品是否会被套餐引用，有则不允许删除
        //根据菜品id查询setmeal_dish表的数据，如果有数据就不能删除
        //select count(*) from setmeal_dish where dishId in (1,2,3)
        Integer count = setmealDishMapper.getCountByDishIds(ids);
        if(count > 0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //3.删除菜品和对应的口味数据
        for (Long id : ids) {
            //删除菜品
            dishMapper.deleteById(id);
            //删除菜品的口味
            dishFlavorMapper.deleteByDishId(id);
        }
    }

//  菜品起售、停售
    @Override
    public void startOrStop(Long id, Integer status) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.update(dish);
        if (status == StatusConstant.DISABLE){
            //如果套餐采用停用操作，则需要对相应套餐停售
            List<Long> dishIds = new ArrayList<>();
            dishIds.add(id);
            // select setmeal_id from setmeal_dish where dish_id in (???)
            List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(dishIds);
            if(setmealIds != null && setmealIds.size() > 0){
                for (Long setmealId : setmealIds) {
                    Setmeal setmeal = Setmeal.builder()
                            .id(setmealId)
                            .status(status)
                            .build();
                    setmealMapper.update(setmeal);
                }
            }

        }
    }

    /*
    * 查询菜品列表
    * */
    @Override
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }
/*
* 根据id查询菜品，并多表查询
* */
    @Override
    public DishVO findById(Long id) {
        //1.根据菜品ID查询菜品Dish数据
        Dish dish = dishMapper.getById(id);
        //2.根据菜品ID查询口味列表数据
        List<DishFlavor> dishFlavors = dishFlavorMapper.getByDishId(id);
        //3.实例DishVO对象，封装菜品和口味列表
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        //封装口味数据
        dishVO.setFlavors(dishFlavors);
        //4.返回DishVO对象
        return dishVO;
    }

    /*
    * 菜品修改，涉及多表查询
    * */
    @Override
    @Transactional
    public void update(DishDTO dishDTO) {
        //1.修改菜品表
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //修改菜品表基本信息
        dishMapper.update(dish);
        //2.处理口味表新数据
        //实际开发的处理逻辑如下：
        //菜品1表直接修改即可
        //多表的思路是先删除，再插入
        //2.1删除菜品id对应的口味列表数据
        dishFlavorMapper.deleteByDishId(dish.getId());
        //2.2遍历传入过来的最新口味列表，设置每个菜品的id
        List<DishFlavor> dishFlavors = dishDTO.getFlavors().stream().map(dishFlavor -> {
            dishFlavor.setDishId(dish.getId());
            return dishFlavor;
        }).collect(Collectors.toList());

        //2.3批量插入最新的口味列表数据
        dishFlavorMapper.saveBatch(dishFlavors);

    }

    /*
    * 条件查询口味和菜品
    * */
    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);
        List<DishVO> dishVOList = new ArrayList<>();
        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());
            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
